package com.inno.subject.domain.service.impl;

import com.inno.subject.domain.entity.SmartQABO;
import com.inno.subject.domain.service.SmartQADomainService;
import com.inno.subject.domain.utils.ApplicationContextUtil;
import com.inno.subject.domain.utils.ChatClientUtil;
import com.inno.subject.domain.websocket.SubjectSocket;
import jakarta.websocket.Session;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.CompletableFuture;

@Service
@RequiredArgsConstructor
@Slf4j
public class SmartQADomainServiceImpl implements SmartQADomainService {
    private final ChatClientUtil chatClientUtil;
    private static final String QA_KYE_WORD = "你是为用户提供全方位帮助的智能伙伴，回答问题逻辑清晰、内容详实，在科技、文化、艺术等领域有深厚积累,如果用户询问你是谁,你需要回答你是InnoClub的智能问答机器人，很高兴为您解惑!  (目前是2025年) ";
    private final ThreadPoolTaskExecutor subjectExecutor;
    @Override
    public void submit(SmartQABO smartQABO) {
        SubjectSocket socket = ApplicationContextUtil.getWebSocket();
        Long currentUser = smartQABO.getCurrentUser();
        Session session = socket.getSession(currentUser);
        if (Objects.isNull(session) || !session.isOpen()){
            return;
        }
        String question = smartQABO.getMessage();
        if (StringUtils.isBlank(question)){
            return;
        }
        List<String> finalList = Collections.synchronizedList(new ArrayList<>());
        CompletableFuture.runAsync(()-> chatClientUtil.streamingCall(question,QA_KYE_WORD, currentUser).subscribe(
                response -> ChatClientUtil.processorSubscribe(response, finalList, socket, session),
                error -> {
                    log.error("智能问答处理失败", error);
                    socket.sendMessage(session, "网络连接出现些小问题，请稍后重试");
                },
                () -> {
                    String finalMessage = finalList.get(finalList.size() - 1);
                    chatClientUtil.addHistoryMessage(finalMessage, currentUser);

                }
        ),subjectExecutor);

    }
}
